<template>
  <div class="app-container">
    <j-dialog
      title="选择发货日期"
      :visible.sync="showAuditTime"
      is-mask
    >
      <div>
        <el-date-picker
          v-model="auditTime"
          align="right"
          unlink-panels
          class="fl1"
          format="yyyy-MM-dd HH:mm:ss"
          value-format="yyyy-MM-dd HH:mm:ss"
          type="datetime"
          placeholder="发货日期"
        />
      </div>
      <div style="width: 100%" class="flex flex-reverse">
        <el-button @click="updatedAuditTime">提交</el-button>
      </div>

    </j-dialog>
    <!--工具栏-->
    <el-dialog title="表格配置"
               :visible.sync="tableConfigShow"
               width="60%">
      <j-table-column-config :columns.sync="currentHeader"  @tabSave="saveHead"/>
    </el-dialog>
    <div class="head-container">
      <div>
        <el-form size="small" label-width="80px" :rules="rules" ref="form" :model="crud.order"
                 :disabled="crud.order.orderStatus==='PASS'">
          <el-row :gutter="10">
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="编码" prop="code">
                <el-input     style="width: 100%" disabled v-model="crud.order.code"></el-input>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="状态">
                <el-select
                  v-model="crud.order.orderStatus"
                  class="filter-item"
                  clearable
                  disabled
                  placeholder="状态"
                  size="small"
                  style="width: 100%;"
                >
                  <el-option
                    v-for="item in dict.common_order_status"
                    :key="item.id"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="打印次数" prop="code">
                <el-input  disabled  style="width: 100%" v-model="crud.order.printCount"></el-input>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="车辆" prop="carId">
                <zSelect     style="width: 100%" :value.sync="crud.order.carId"
                             :showName="crud.order.carName"
                             :disabled="crud.order.orderStatus==='PASS'" url="api/dropDown/basCarList" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="10">
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="司机" prop="driverUserId">
                <zSelect     style="width: 100%" :value.sync="crud.order.driverUserId"
                             :showName="crud.order.driverUserName"
                             :disabled="crud.order.orderStatus==='PASS'" url="api/dropDown/sysUserList" :params="{businessAttr:'5'}" />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="跟车" prop="">
                <zSelect  :multiple="multiple"  :disabled="crud.order.orderStatus==='PASS'"
                          style="width: 100%" :value.sync="crud.order.followUserIds" :showName="crud.order.followUserName"
                          :label="crud.order.followUserName" url="api/dropDown/sysUserList" :params="{businessAttr:'6'}"/>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="装车日期" prop="busDate">
                <el-date-picker
                  v-model="crud.order.busDate"
                  type="date"
                  size="small"
                  :disabled="crud.order.orderStatus==='PASS'"
                  class="date-item"
                  style="width: 100%;"
                  format="yyyy - MM - dd"
                  value-format="yyyy-MM-dd"
                />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="备注" prop="remark">
                <el-input      :disabled="crud.order.orderStatus==='PASS'"  style="width: 100%" v-model="crud.order.remark"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="10">
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="是否验收" prop="isAccept">
                <el-select
                  v-model="crud.order.isAccept"
                  class="filter-item"
                  clearable
                  disabled
                  placeholder="状态"
                  size="small"
                  style="width: 100%;"
                >
                  <el-option
                    v-for="item in dict.common_yes_or_no"
                    :key="item.id"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="部门" prop="code">
                <el-input     style="width: 100%" disabled v-model="crud.order.deptName"></el-input>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="商品回收箱数" label-width="100px" prop="code">
                <el-input     style="width: 100%" disabled v-model="crud.order.goodsRecycleBoxCount"></el-input>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="商品回收含税金额" label-width="110px" prop="code">
                <el-input     style="width: 100%" disabled v-model="crud.order.goodsRecycleTaxAmount"></el-input>
              </el-form-item>
            </el-col>
            <div class="isReturnBox" v-if="crud.order.isReturnBoxPass == 1">已回箱</div>
          </el-row>
          <el-row>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="商品回收未税金额" label-width="110px" prop="code">
                <el-input     style="width: 100%" disabled v-model="crud.order.goodsRecycleNoTaxAmount"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <crudOperation :permission="permission">
        <el-button
          slot="left"
          class="filter-item"
          size="mini"
          type="primary"
          :disabled="crud.order.orderStatus==='PASS'"
          @click="toPicking(crud.selections)"
          v-permission="permission.add"
        >
          保存
        </el-button>
        <el-button
          v-if="crud.order.orderStatus==='PASS' && crud.order.isAccept == 0"
          :disabled="$route.params.id == 'add' "
          :loading="crud.downloadLoading"
          class="filter-item"
          size="mini"
          slot="left"
          type="success"
          @click="isshowcustomer = true"
          v-permission="permission.accept"
        >验收</el-button>
        <el-button
          :disabled="$route.params.id == 'add'"
          :loading="crud.downloadLoading"
          class="filter-item"
          size="mini"
          slot="left"
          type="danger"
          @click="toUnAccept($route.params.id)"
          v-permission="permission.accept"
        >反验收</el-button>
        <el-button
          :loading="crud.downloadLoading"
          class="filter-item"
          size="mini"
          type="warning"
          @click="crud.preView"
          v-permission="permission.print"
        >打印</el-button>
        <el-button
          :loading="crud.downloadLoading"
          class="filter-item"
          size="mini"
          type="warning"
          @click="crud.preView1"
          v-permission="permission.print"
        >打印预览</el-button>
        <span
          slot="right"
        >
          <el-button
            slot="right"
            class="filter-item"
            size="mini"
            @click="goToAdd()"
            :disabled="$route.params.id == 'add' || crud.order.orderStatus==='PASS'"
            v-permission="permission.copy"
          >
            追加
          </el-button>
            <!--        <el-button-->
            <!--          slot="right"-->
            <!--          class="filter-item"-->
            <!--          size="mini"-->
            <!--          @click="handleReturnBox(crud)"-->
            <!--          :disabled="$route.params.id == 'add' || crud.order.orderStatus==='PASS'"-->
            <!--          v-permission="permission.copy"-->
            <!--        >-->
            <!--          回箱入库-->
            <!--        </el-button>-->
          <el-button
            slot="right"
            class="filter-item"
            size="mini"
            @click="showReturn = true"
            v-if="crud.order.orderStatus==='PASS' && crud.order.isAccept == 0"
            v-permission="permission.returnBoxPass"
          >
            回箱审核
          </el-button>
            <el-button
              slot="right"
              class="filter-item"
              size="mini"
              @click="unReturnBoxHandle"
              v-if="crud.order.orderStatus==='PASS' && crud.order.isAccept == 0"
              v-permission="permission.returnBoxReject"
            >
              反审回箱
            </el-button>
          <el-button
            slot="right"
            class="filter-item"
            size="mini"
            @click="saveReceipt"
            v-if="crud.order.isAccept == 0"
            v-permission="permission.batchCustomerReceipt"
          >
            保存收款
          </el-button>
          <el-button
            slot="right"
            class="filter-item"
            size="mini"
            @click="batchCollectionShow = true"
            v-if="crud.order.isAccept == 0"
            v-permission="permission.batchCustomerReceipt"
          >
            批量收款
          </el-button>
            <!--        <el-button-->
            <!--          slot="right"-->
            <!--          class="filter-item"-->
            <!--          size="mini"-->
            <!--          @click="handleUnReturnBox()"-->
            <!--          :disabled="$route.params.id == 'add' || crud.order.orderStatus==='PASS'"-->
            <!--          v-permission="permission.copy"-->
            <!--        >-->
            <!--          回箱反审-->
            <!--        </el-button>-->
          <el-button
            slot="right"
            class="filter-item"
            size="mini"
            type="warning"
            icon="el-icon-notebook-2"
            @click="tabInvoiceType('logisticsLoad',0,'salesOrderPrint')"
            v-permission="permission.salesOrderPrint"
          >销售单打印</el-button>
          <el-button
            slot="right"
            class="filter-item"
            size="mini"
            type="warning"
            icon="el-icon-notebook-2"
            @click="tabInvoiceType('logisticsLoad',1,'salesOrderPrint')"
            v-permission="permission.salesOrderPrint"
          >销售单打印预览</el-button>
          <el-button
            slot="right"
            class="filter-item"
            size="mini"
            type="warning"
            icon="el-icon-notebook-2"
            @click="tabInvoiceType('logisticsLoad',0,'logisticsLoadGoodsPrint')"
            v-permission="permission.goodsPrint"
          >商品汇总打印</el-button>
          <el-button
            slot="right"
            class="filter-item"
            size="mini"
            type="warning"
            icon="el-icon-notebook-2"
            @click="tabInvoiceType('logisticsLoad',1,'logisticsLoadGoodsPrint')"
            v-permission="permission.goodsPrint"
          >商品汇总打印预览</el-button>
          <el-button
            slot="right"
            class="filter-item"
            size="mini"
            @click="removeStorage"
          >
            清除宽度缓存
          </el-button>
          <el-button
            slot="right"
            v-permission="permission.removeCustomer"
            :disabled="isDel"
            :loading="crud.delAllLoading"
            class="filter-item"
            size="mini"
            type="danger"
            @click="delAddRowOrder"
          >
            删除
          </el-button>
          <el-button
            slot="right"
            :disabled="crud.order.isAccept == '1'"
            class="filter-item"
            size="mini"
            type="danger"
            @click="showAuditTime = true"
          >
            更新发货日期
          </el-button>
          <el-button
            slot="right"
            v-if="idDate"
            class="filter-item"
            size="mini"
            type="warning"
            @click="detailJump('up')"
          >上一页</el-button>
          <el-button
            slot="right"
            v-if="idDate"
            class="filter-item"
            size="mini"
            type="warning"
            @click="detailJump('down')"
          >下一页</el-button>
          <el-button
            slot="right"
            v-permission="permission.orderRecycle"
            :disabled="isRec"
            :loading="crud.delAllLoading"
            class="filter-item"
            size="mini"
            type="danger"
            @click="orderRecycle"
          >
            单据回收
          </el-button>
          <el-button
            slot="right"
            v-permission="permission.confirmRecycle"
            :disabled="isRec"
            :loading="crud.delAllLoading"
            class="filter-item"
            size="mini"
            type="danger"
            @click="confirmRecycle"
          >
            确认回收
          </el-button>

          <el-button
            slot="right"
            v-permission="permission.applyDebt"
            :disabled="checkDebt(0)"
            :loading="crud.delAllLoading"
            class="filter-item"
            size="mini"
            type="danger"
            @click="applyDebt"
          >
          申请欠款
        </el-button>
        <el-button
          slot="right"
          v-permission="permission.confirmDebt"
          :disabled="checkDebt(1)"
          :loading="crud.delAllLoading"
          class="filter-item"
          size="mini"
          type="danger"
          @click="confirmDebt"
        >
          确认欠款
        </el-button>

        </span>
      </crudOperation>
      <el-dialog
        title="请选择打印模板"
        :visible.sync="pringDialog"
        width="30%"
      >
        <jPrintConfig groupId="logisticsLoad"
                      v-if="pringDialog"
                      @getPrintId="print"
        ></jPrintConfig>
      </el-dialog>

      <el-dialog
        title="收款银行"
        :visible.sync="showBankListDialog"
        width="40%"
        v-dialog-drag
      >
        <div>
          <el-form :model="customerReceiptBankList" ref="numberValidateForm" label-width="100px" class="demo-ruleForm">
            <el-row v-for="(row,index) in customerReceiptBankList.customerReceiptBankList">
              <el-col :span="10">
                <el-form-item
                  label="银行名称"
                >

                  <span v-if="crud.order.isAccept === '1'">{{ row.bankName }}</span>
                  <zSelect v-else :showName="row.bankName" :value.sync="row.bankId"  url="api/basBank/getBasBanksById"
                           style="width:  100%;"
                           :params="{page: null,size: null,sort: 'seq desc'}"  labelKey="bankName" valueKey="bankId"
                           @change="e=>changeCustomerReceiptBankListName(e,row)"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="10">
                <el-form-item
                  label="收款金额"
                >
                  <span v-if="crud.order.isAccept === '1'">{{ row.bankName }}</span>
                  <el-input v-else v-model="row.taxAmount"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="4">
                <el-tooltip v-permission="permission.removeCustomer" class="item" content="删除" effect="light" placement="top">
                  <i class="el-icon-delete opration_icon_btn" @click="delBank(customerReceiptBankList,index)" style="font-size: 30px;margin-left: 10px" type="primary"/>
                </el-tooltip>
              </el-col>
            </el-row>
            <div>
              <el-button  v-if="crud.order.isAccept !== '1'" @click="addBank">添加银行</el-button>
              <el-button @click="saveBank">确定</el-button>
            </div>
          </el-form>
        </div>
      </el-dialog>

      <!--      状态切换  -->
      <el-tabs ref="tab" v-model="query.pickStatus" @tab-click="handleClickPickStatus">
        <el-tab-pane label="客户汇总" name="0">
          <el-table ref="table1" stripe border
                    :row-class-name="crud.tableRowClassName"
                    v-loading="crud.loading" :data="customerList"
                    size="small" style="width: 100%;"
                    show-summary
                    @header-dragend="changeColWidthMany"
                    v-draghead="setHeadName('customerList')"
                    :summary-method="crud.sumRow"
                    @selection-change="selectionChangeHandler"
                    @row-dblclick="toDetailPlus($event)">
            <el-table-column type="selection" width="60" />
            <el-table-column type="index" width="60" label="序号"/>
            <el-table-column v-if="item.visible"  v-for="(item, index) in header.customerList" :key="`col_${index}`" :prop="item.prop" :label="columnLabel(item)" :width="item.width + 'px'" ><template slot-scope='{row,$index}'><span v-if='item.type == 1'>{{ row[`${item.prop}`] }}</span><span v-else-if='item.type == 2' >{{ parseTime(row[`${item.prop}`])}}</span><span v-else-if='item.type == 3' >{{ getDict(`this.dict.label.${item.dictionary}[${row[item.prop]}]`) }}</span><span v-else-if="item.type == 4"><span v-if="item.prop == 'receiptAmount'"> <span v-if="$index !== rowIndex" style="color: blue">{{row.receiptAmount}}</span> <el-input v-else v-model="row.receiptAmount"></el-input> </span><span v-if="item.prop == 'bankName'"> <span v-if="$index !== rowIndex">{{ row.bankName }}</span> <zSelect v-else :showName="row.bankName" :value.sync="row.bankId" url="api/basBank/getBasBanksById" style="width: 100%;" @change="e=>setBank(e,row)" :params="{sort: 'seq desc'}" labelKey="bankName" valueKey="bankId" /> </span><span v-if="item.prop == 'receiptRemark'"> <span v-if="$index !== rowIndex">{{row.receiptRemark}}</span> <el-input v-else v-model="row.receiptRemark"></el-input> </span><span v-if="item.prop == 'customerReceiptBankList'"> <span class="banks" @click="setBankList(row)"> {{ row.customerReceiptBankList.map(item=>item.bankName).join(',') }} </span> </span><span v-if="item.prop == 'receiptDate'"> <span v-if="$index !== rowIndex">{{ row.receiptDate}}</span> <el-date-picker v-else v-model="row.receiptDate" align="right" unlink-panels class="fl1" format="yyyy-MM-dd HH:mm:ss" value-format="yyyy-MM-dd HH:mm:ss" type="datetime" placeholder="收款日期" /> </span><span v-if="item.prop == 'returnBoxDate'"> <span>{{ parseTime(row.returnBoxDate) }}</span> </span></span> </template> </el-table-column> <el-table-column label="操作" fixed="right" width="200px" align="center"> <template slot-scope="scope"> <el-tooltip v-permission="permission.customerReceipt" class="item" content="收款" effect="light" placement="top"> <i class="el-icon-edit-outline opration_icon_btn" type="primary" @click="collection(scope.row)"/> </el-tooltip> <el-tooltip v-permission="permission.removeCustomer" class="item" content="多银行收款" effect="light" placement="top"> <i class="opration_icon_btn el-icon-plus" type="primary" @click="setBankList(scope.row)"/> </el-tooltip> <el-tooltip v-permission="permission.removeCustomer" class="item" content="删除" v-if="crud.order.orderStatus!=='PASS'" effect="light" placement="top"> <i class="el-icon-delete opration_icon_btn" type="primary" @click="delAddRow(scope)"/> </el-tooltip> </template> </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="单据汇总" name="1">
          <el-table ref="tableSum"
                    show-summary
                    @header-dragend="changeColWidthMany"
                    :row-class-name="crud.tableRowClassName"
                    v-draghead="setHeadName('orderList')"
                    :summary-method="crud.sumRow"
                    stripe border v-loading="crud.loading" :data="orderList" size="small" style="width: 100%;" @selection-change="selectionChangeHandler" @row-dblclick="toDetailPlus($event)"
                    >
            <el-table-column type="selection" width="60" />
            <el-table-column type="index" width="60" label="序号"/>
            <el-table-column v-if="item.visible" v-for="(item, index) in header.orderList" :key="`col_${index}`" :prop="item.prop" :label="columnLabel(item)" :width="item.width + 'px'" ><template slot-scope='{row,$index}'><span v-if='item.type == 1'>{{ row[`${item.prop}`] }}</span><span v-else-if='item.type == 2' >{{ parseTime(row[`${item.prop}`])}}</span><span v-else-if='item.type == 3' >{{ getDict(`this.dict.label.${item.dictionary}[${row[item.prop]}]`) }}</span><span v-else-if="item.type == 4"><span v-if="item.prop == 'salesOrderCode'"> <span :class="{'green':(row.isPrint == 1),'old':(row.isPrint == 0)}" style="cursor: pointer;text-decoration: #409eff" @click="goToPage(0,row.salesOrderId)">{{ row.salesOrderCode }}</span> </span><span v-if="item.prop == 'sourceCode'"> <span style="color:#409eff;cursor: pointer;text-decoration: #409eff" @click="goToPage(row.sourceType,row.sourceId)">{{ row.sourceCode }}</span> </span><span v-if="item.prop == 'pickStatuse'"> {{ dict.label.t_ware_sales_invoice_pick_status[row.pickStatus] }} </span><span v-if="item.prop == 'auditTime'"> <span>{{ parseTime(row.auditTime) }}</span> </span><span v-if="item.prop == 'isReceipt'"> <el-tag>{{ dictName(dict.common_yes_or_no,row.isReceipt) }}</el-tag> </span><span v-if="item.prop == 'isReceipt'"> <el-tag>{{ dictName(dict.common_yes_or_no,row.isRecycle) }}</el-tag> </span><span v-if="item.prop == 'cancelStatus'"> <el-tag>{{ dictName(dict.common_cancel_status,row.cancelStatus) }}</el-tag> </span></span> </template> </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="商品汇总" name="2">
          <el-table ref="table"
                    show-summary
                    @header-dragend="changeColWidthMany"
                    v-draghead="setHeadName('goodsList')"
                    :summary-method="crud.sumRow"
                    stripe border v-loading="crud.loading" :data="goodsList" size="small" style="width: 100%;" @selection-change="selectionChangeHandler" @row-dblclick="toDetailPlus($event)">
            <el-table-column type="selection" width="60" />
            <el-table-column type="index" width="60" label="序号"/>
            <el-table-column v-if="item.visible" v-for="(item, index) in header.goodsList" :key="`col_${index}`" :prop="item.prop" :label="columnLabel(item)" :width="item.width + 'px'"  ><template slot-scope='{row,$index}'><span v-if='item.type == 1'>{{ row[`${item.prop}`] }}</span><span v-else-if='item.type == 2' >{{ parseTime(row[`${item.prop}`])}}</span><span v-else-if='item.type == 3' >{{ getDict(`this.dict.label.${item.dictionary}[${row[item.prop]}]`) }}</span><span v-else-if="item.type == 4"><span v-if="item.prop == 'producedDate'"> <span>{{ parseTime(row.producedDate) }}</span> </span><span v-if="item.prop == 'goodsRecycleBoxNum'"> <span >{{ row.goodsRecycleBoxNum }}{{ row.boxUnitName }}</span> <span >{{ row.goodsRecycleMainNum }}{{ row.mainUnitName }}</span> </span><span v-if="item.prop == 'deadlineDate'"> <span>{{ parseTime(row.deadlineDate) }}</span> </span><span v-if="item.prop == 'boxNum'"> <span >{{ row.boxNum }}{{ row.boxUnitName }}</span> <span >{{ row.mainNum }}{{ row.mainUnitName }}</span> </span></span> </template> </el-table-column>              <!--            <el-table-column label="操作" fixed="right" width="150px"-->
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="客户商品汇总" name="5">
          <el-table ref="table"
                    show-summary
                    @header-dragend="changeColWidthMany"
                    v-draghead="setHeadName('customerGoodsList')"
                    :summary-method="crud.sumRow"
                    stripe border v-loading="crud.loading" :data="customerGoodsList" size="small" style="width: 100%;" @selection-change="selectionChangeHandler" @row-dblclick="toDetailPlus($event)">
            <el-table-column type="selection" width="60" />
            <el-table-column type="index" width="60" label="序号"/>
            <el-table-column v-if="item.visible" v-for="(item, index) in header.customerGoodsList" :key="`col_${index}`" :prop="item.prop" :label="columnLabel(item)" :width="item.width + 'px'"  ><template slot-scope='{row,$index}'><span v-if='item.type == 1'>{{ row[`${item.prop}`] }}</span><span v-else-if='item.type == 2' >{{ parseTime(row[`${item.prop}`])}}</span><span v-else-if='item.type == 3' >{{ getDict(`this.dict.label.${item.dictionary}[${row[item.prop]}]`) }}</span><span v-else-if="item.type == 4"><span v-if="item.prop == 'goodsRecycleBoxNum'"> <span >{{ row.goodsRecycleBoxNum }}{{ row.boxUnitName }}</span> <span >{{ row.goodsRecycleMainNum }}{{ row.mainUnitName }}</span> </span><span v-if="item.prop == 'boxNum'"> <span >{{ row.boxNum }}{{ row.boxUnitName }}</span> <span >{{ row.mainNum }}{{ row.mainUnitName }}</span> </span></span> </template> </el-table-column>          </el-table>
        </el-tab-pane>
        <el-tab-pane label="回箱单据汇总" name="3">
          <el-table ref="returnBillTable"
                    show-summary
                    @header-dragend="changeColWidthMany"
                    v-draghead="setHeadName('returnBoxOrderList')"
                    @contextmenu.native="showMenu"
                    @row-click="selectRow"
                    highlight-current-row="highlight-current-row"
                    :summary-method="crud.sumRow"
                    stripe border v-loading="crud.loading" :data="returnBoxOrderList" size="small" style="width: 100%;" @selection-change="selectionChangeHandler" @row-dblclick="toDetailPlus($event)">
            <el-table-column type="selection" width="60" />
            <el-table-column type="index" width="60" label="序号"/>
            <el-table-column v-if="item.visible" v-for="(item, index) in header.returnBoxOrderList" :key="`col_${index}`" :prop="item.prop" :label="columnLabel(item)" :width="item.width + 'px'" ><template slot-scope='{row,$index}'><span v-if='item.type == 1'>{{ row[`${item.prop}`] }}</span><span v-else-if='item.type == 2' >{{ parseTime(row[`${item.prop}`])}}</span><span v-else-if='item.type == 3' >{{ getDict(`this.dict.label.${item.dictionary}[${row[item.prop]}]`) }}</span><span v-else-if="item.type == 4"></span> </template> </el-table-column>
          </el-table>
          <j-bill-detail
            addUrl="/api/wareReturnBottleBox/addOrSave"
            delUrl="/api/wareReturnBottleBox/removeDetail"
            update
            :order="detailOrder"
            url="/api/wareReturnBottleBox/detail"
            type="get"
            :isAdd="isChildrenAdd"
            orderGoodsType="SALE_RETURN"
            :headerQuery="headerQuery"
            :params="detailParams"
            :autoList="['warehouse']"
            @parenUpdate="crud.refresh"
            isSelected
            isSubmit
            isEditWithoutReject
            isIgnoreReturnBoxPass
            :islogistiLoad="true"
          ></j-bill-detail>
        </el-tab-pane>
        <el-tab-pane label="回箱商品汇总" name="4">
          <el-table ref="table"
                    show-summary
                    @header-dragend="changeColWidthMany"
                    v-draghead="setHeadName('returnBoxGoodsList')"
                    :summary-method="crud.sumRow"
                    stripe border v-loading="crud.loading" :data="returnBoxGoodsList" size="small" style="width: 100%;" @selection-change="selectionChangeHandler" @row-dblclick="toDetailPlus($event)">
            <el-table-column type="selection" width="60" />
            <el-table-column type="index" width="60" label="序号"/>
            <el-table-column v-if="item.visible" v-for="(item, index) in header.returnBoxGoodsList" :key="`col_${index}`" :prop="item.prop" :label="columnLabel(item)" :width="item.width + 'px'" ><template slot-scope='{row,$index}'><span v-if='item.type == 1'>{{ row[`${item.prop}`] }}</span><span v-else-if='item.type == 2' >{{ parseTime(row[`${item.prop}`])}}</span><span v-else-if='item.type == 3' >{{ getDict(`this.dict.label.${item.dictionary}[${row[item.prop]}]`) }}</span><span v-else-if="item.type == 4"><span v-if="item.prop == 'boxNum'"> <span >{{ row.boxNum }}{{ row.boxUnitName }}</span> <span >{{ row.mainNum }}{{ row.mainUnitName }}</span> </span></span> </template> </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="客户回箱商品汇总" name="6">
          <el-table ref="table"
                    show-summary
                    @header-dragend="changeColWidthMany"
                    v-draghead="setHeadName('returnBoxCustomerGoodsList')"
                    :summary-method="crud.sumRow"
                    stripe border v-loading="crud.loading" :data="returnBoxCustomerGoodsList" size="small" style="width: 100%;" @selection-change="selectionChangeHandler" @row-dblclick="toDetailPlus($event)">
            <el-table-column type="selection" width="60" />
            <el-table-column type="index" width="60" label="序号"/>
            <el-table-column v-if="item.visible" v-for="(item, index) in header.returnBoxCustomerGoodsList" :key="`col_${index}`" :prop="item.prop" :label="columnLabel(item)" :width="item.width + 'px'"  ><template slot-scope='{row,$index}'><span v-if='item.type == 1'>{{ row[`${item.prop}`] }}</span><span v-else-if='item.type == 2' >{{ parseTime(row[`${item.prop}`])}}</span><span v-else-if='item.type == 3' >{{ getDict(`this.dict.label.${item.dictionary}[${row[item.prop]}]`) }}</span><span v-else-if="item.type == 4"><span v-if="item.prop == 'boxNum'"> <span >{{ row.boxNum }}{{ row.boxUnitName }}</span> <span >{{ row.mainNum }}{{ row.mainUnitName }}</span> </span></span> </template> </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="回箱汇总单据" name="7">
          <el-table ref="wareReturnBottleBoxCollectTable"
                    show-summary
                    @header-dragend="changeColWidthMany"
                    v-draghead="setHeadName('returnBoxCollectOrderList')"
                    @row-click="wareReturnBottleBoxCollectSelectRow"
                    highlight-current-row="highlight-current-row"
                    :summary-method="crud.sumRow"
                    stripe border v-loading="crud.loading" :data="returnBoxCollectOrderList" size="small" style="width: 100%;" @selection-change="selectionChangeHandler" @row-dblclick="toDetailPlus($event)">
            <el-table-column type="selection" width="60" />
            <el-table-column type="index" width="60" label="序号"/>
            <el-table-column v-if="item.visible" v-for="(item, index) in header.returnBoxCollectOrderList" :key="`col_${index}`" :prop="item.prop" :label="columnLabel(item)" :width="item.width + 'px'"  ><template slot-scope='{row,$index}'><span v-if='item.type == 1'>{{ row[`${item.prop}`] }}</span><span v-else-if='item.type == 2' >{{ parseTime(row[`${item.prop}`])}}</span><span v-else-if='item.type == 3' >{{ getDict(`this.dict.label.${item.dictionary}[${row[item.prop]}]`) }}</span><span v-else-if="item.type == 4"></span> </template> </el-table-column>
          </el-table>
          <j-bill-detail
            addUrl="/api/wareReturnBottleBoxCollect/addOrSave"
            delUrl="/api/wareReturnBottleBoxCollect/removeDetail"
            update
            :order="wareReturnBottleBoxCollectDetailOrder"
            url="/api/wareReturnBottleBoxCollect/detail"
            type="get"
            :isAdd="isChildrenAdd"
            orderGoodsType="SALE_RETURN"
            :headerQuery="wareReturnBottleBoxCollectDetail"
            :params="wareReturnBottleBoxCollectDetailParams"
            :autoList="['warehouse']"
            @parenUpdate="crud.refresh"
            isSelected
            isSubmit
            typeName="wareReturnBottleBoxCollect"
            :islogistiLoad="true"
          ></j-bill-detail>
        </el-tab-pane>
        <el-tab-pane label="验收商品汇总" name="8">
          <el-table ref="acceptGoodsTable"
                    show-summary
                    @header-dragend="changeColWidthMany"
                    v-draghead="setHeadName('acceptGoodsList')"
                    :summary-method="crud.sumRow"
                    stripe border v-loading="crud.loading" :data="acceptGoodsList" size="small" style="width: 100%;" @selection-change="selectionChangeHandler" @row-dblclick="toDetailPlus($event)">
            <el-table-column type="selection" width="60" />
            <el-table-column type="index" width="60" label="序号"/>
            <el-table-column v-if="item.visible"  v-for="(item, index) in header.acceptGoodsList" :key="`col_${index}`" :prop="item.prop" :label="columnLabel(item)" :width="item.width + 'px'"  >
              <template slot-scope='{row,$index}'>
              <span :class="row.type==='退货'?'red':''" v-if='item.type == 1'> {{ row[`${item.prop}`] }}</span>
              <span :class="row.type==='退货'?'red':''" v-else-if='item.type == 2' >{{ parseTime(row[`${item.prop}`])}}</span>
              <span :class="row.type==='退货'?'red':''" v-else-if='item.type == 3' >{{ getDict(`this.dict.label.${item.dictionary}[${row[item.prop]}]`) }}</span>
              <span  :class="row.type==='退货'?'red':''" v-else-if="item.type == 4">
                <span v-if="item.prop == 'acceptGoodsCount'">
                  <span >{{ row.acceptBoxNum }}{{ row.boxUnitName }}
                  </span> <span >{{ row.acceptMainNum }}{{ row.mainUnitName }}</span>
                </span><span v-if="item.prop == 'goodsRecycleBoxNum'">
                <span >{{ row.goodsRecycleBoxNum }}{{ row.boxUnitName }}</span>
                <span >{{ row.goodsRecycleMainNum }}{{ row.mainUnitName }}</span>
              </span></span> </template> </el-table-column>


          </el-table>
        </el-tab-pane>
      </el-tabs>
      <el-dialog
        title="请选择打印模板"
        :visible.sync="crud.printConfig.pringDialog"
        width="30%"
      >
        <jPrintConfig groupId="logisticsLoad"
                      v-if="crud.printConfig.pringDialog"
                      @getPrintId="crud.detailedPrint"
                      :isPreview="crud.printConfig.isPreview"
        ></jPrintConfig>
      </el-dialog>
      <el-dialog
        title="批量收款"
        :visible.sync="batchCollectionShow"
        width="70%"
      >
        <el-table ref="collectTable"
                  stripe
                  border
                  @row-click="selectRow01"
                  :row-class-name="crud.tableRowClassName"
                  v-loading="crud.loading" :data="customerList"
                  size="small" style="width: 100%;"
                  show-summary
                  height="500"

                  :summary-method="sumRow"
                  @selection-change="selectionChangeHandler01"
                  @header-dragend="(newWidth, old, column)=>{changWidth(newWidth, old, column,'customerSum')}"
                  @row-dblclick="toDetailPlus($event)">
          <el-table-column type="selection" width="60" />
          <el-table-column type="index" width="60" label="序号"/>
          <el-table-column v-if="columns.visible('customerCode')" :width="tableWidth.customerSum.customerCode" prop="customerCode" label="客户编号" />
          <el-table-column v-if="columns.visible('customerName')" :width="tableWidth.customerSum.customerName" prop="customerName" label="客户名称" />
          <el-table-column v-if="columns.visible('orderNum')" :width="tableWidth.customerSum.orderNum"  prop="orderNum" label="单据数" />
          <el-table-column v-if="columns.visible('taxAmount')"  :width="tableWidth.customerSum.taxAmount" prop="taxAmount" label="商品金额" />
          <el-table-column v-if="columns.visible('emptyBoxTaxAmount')" :width="tableWidth.customerSum.emptyBoxTaxAmount"  prop="emptyBoxTaxAmount" label="塑箱金额" />
          <el-table-column v-if="columns.visible('returnBoxTaxAmount')" :width="tableWidth.customerSum.returnBoxTaxAmount"  prop="returnBoxTaxAmount" label="回箱金额" />
          <el-table-column v-if="columns.visible('receiveAmount')"  :width="tableWidth.customerSum.receiveAmount" prop="receiveAmount" label="实际应收金额" />
          <el-table-column v-if="columns.visible('boxCount')"  :width="tableWidth.customerSum.boxCount" prop="boxCount" label="箱数" />
          <el-table-column v-if="columns.visible('returnBoxBoxCount')" :width="tableWidth.customerSum.returnBoxBoxCount"  prop="returnBoxBoxCount" label="回箱箱数" />
          <el-table-column v-if="columns.visible('volume')" :width="tableWidth.customerSum.volume"  prop="volume" label="体积" />
          <el-table-column v-if="columns.visible('weight')" :width="tableWidth.customerSum.weight"  prop="weight" label="重量" />
          <el-table-column v-if="columns.visible('receiptAmount')" :width="tableWidth.customerSum.receiptAmount"  prop="receiveAmount" label="收款金额" >
          </el-table-column>
          <el-table-column v-if="columns.visible('bankName')" :width="tableWidth.customerSum.bankName"  prop="bankName" label="收款银行" >
          </el-table-column>
          <el-table-column v-if="columns.visible('returnBoxDate')" :width="tableWidth.customerSum.returnBoxDate"  prop="returnBoxDate" label="回箱时间">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.returnBoxDate) }}</span>
            </template>
          </el-table-column>

          <el-table-column v-if="columns.visible('receiptDate')" :width="tableWidth.customerSum.receiptDate"  prop="receiptDate" label="收款时间">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.receiptDate) }}</span>
            </template>
          </el-table-column>
          <el-table-column v-if="columns.visible('receiptRemark')" :width="tableWidth.customerSum.receiptRemark"  prop="receiptRemark" label="收款备注" />
          <el-table-column v-if="columns.visible('remark')" :width="tableWidth.customerSum.remark"  prop="remark" label="备注" />
          <el-table-column v-if="columns.visible('receiptCode')" :width="tableWidth.customerSum.receiptCode"  prop="receiptCode" label="收款单号" />
        </el-table>
        <div style="padding-top: 20px">
          <el-form :model="batchCollection" :rules="collectionForm" ref="collectionForm" label-width="100px" class="demo-ruleForm">
            <el-row>
              <el-col :xs="24" :sm="8" :md="8" :lg="8" :xl="8">
                <el-form-item prop="receiptDate" label="收款日期" >
                  <el-date-picker
                    v-model="batchCollection.receiptDate"
                    align="right"
                    unlink-panels
                    class="fl1"
                    format="yyyy-MM-dd HH:mm:ss"
                    value-format="yyyy-MM-dd HH:mm:ss"
                    type="datetime"
                    placeholder="收款日期"
                  />
                  <!--                    <el-date-picker-->
                  <!--                      v-model="batchCollection.receiptDate"-->
                  <!--                      type="date"-->
                  <!--                      size="small"-->
                  <!--                      class="date-item"-->
                  <!--                      style="width: 100%;"-->
                  <!--                      format="yyyy - MM - dd"-->
                  <!--                      value-format="yyyy-MM-dd"-->
                  <!--                    />-->
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="8" :md="8" :lg="8" :xl="8">
                <el-form-item prop="bankId" label="银行" >
                  <zSelect :value.sync="batchCollection.bankId"
                           url="api/dropDown/basBankList"
                           :params="{sort: 'seq desc'}"
                           style="width:100%;"
                  />
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="8" :md="8" :lg="8" :xl="8">
                <el-form-item  label="收款金额" >
                  <el-input disabled
                            v-model="batchCollection.receiptAmount"/>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label="收款备注">
                  <el-input type="textarea" v-model="batchCollection.receiptRemark"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row class="flex flex-reverse" style="padding-top: 30px">
              <el-button type="primary" @click="batchCollectionSave">提交</el-button>
            </el-row>
          </el-form>
        </div>
      </el-dialog>
      <j-dialog
        title="客户汇总"
        :visible.sync="isshowcustomer"
        style="width: 920px"
        isMask
      >
        <el-table ref="table"  border
                  :row-class-name="crud.tableRowClassName"
                  v-loading="crud.loading" :data="customerList"
                  size="small" style="width: 100%;"
                  show-summary
                  :row-style="isRed"
                  :summary-method="crud.sumRow"
                  height="500"
        >
          <el-table-column type="index" width="60" label="序号"/>
          <el-table-column v-if="columns.visible('customerCode')" :width="200" prop="customerCode" label="客户编号" />
          <el-table-column v-if="columns.visible('customerName')" :width="200" prop="customerName" label="客户名称" />
          <el-table-column v-if="columns.visible('orderNum')" :width="tableWidth.customerSum.orderNum"  prop="orderNum" label="单据数" />
          <!--        <el-table-column v-if="columns.visible('taxAmount')"  :width="tableWidth.customerSum.taxAmount" prop="taxAmount" label="商品金额" />-->
          <!--        <el-table-column v-if="columns.visible('emptyBoxTaxAmount')" :width="tableWidth.customerSum.emptyBoxTaxAmount"  prop="emptyBoxTaxAmount" label="塑箱金额" />-->
          <el-table-column v-if="columns.visible('returnBoxTaxAmount')" :width="tableWidth.customerSum.returnBoxTaxAmount"  prop="returnBoxTaxAmount" label="回箱金额" />
          <el-table-column v-if="columns.visible('receiveAmount')"  :width="tableWidth.customerSum.receiveAmount" prop="receiveAmount" label="实际应收金额" />
          <!--        <el-table-column v-if="columns.visible('boxCount')"  :width="tableWidth.customerSum.boxCount" prop="boxCount" label="箱数" />-->
          <!--        <el-table-column v-if="columns.visible('returnBoxBoxCount')" :width="tableWidth.customerSum.returnBoxBoxCount"  prop="returnBoxBoxCount" label="回箱箱数" />-->
          <!--            <el-table-column v-if="columns.visible('volume')" :width="tableWidth.customerSum.volume"  prop="volume" label="体积" />-->
          <!--            <el-table-column v-if="columns.visible('weight')" :width="tableWidth.customerSum.weight"  prop="weight" label="重量" />-->
          <el-table-column v-if="columns.visible('receiptAmount')" :width="tableWidth.customerSum.receiptAmount"  prop="receiptAmount" label="收款金额" >
            <template slot-scope="scope">
              <span  style="color: blue">{{scope.row.receiptAmount}}</span>
            </template>
          </el-table-column>
        </el-table>
        <div style="width: 100%;margin-top: 30px" class="flex flex-reverse ">
          <el-button
            :disabled="$route.params.id == 'add' "
            :loading="crud.downloadLoading"
            class="filter-item"
            size="mini"
            slot="left"
            type="success"
            @click="toAccept($route.params.id)"
            v-permission="permission.accept"
          >验收</el-button>
        </div>
      </j-dialog>
      <right-click-menu @tableConfig="tableConfig" @delBill="delBill" @addBill="addBill"  :options.sync="rightClickMenuConfig"></right-click-menu>
      <el-dialog
        title="确认回箱商品"
        :visible.sync="showReturn"
        width="60%"
      >
        <el-table ref="table"
                  show-summary
                  :summary-method="crud.sumRow"
                  @header-dragend="(newWidth, old, column)=>{changWidth(newWidth, old, column,'returnBoxGoodsSum')}"
                  stripe border v-loading="crud.loading" :data="returnBoxGoodsList" size="small" style="width: 100%;" @selection-change="selectionChangeHandler" @row-dblclick="toDetailPlus($event)">
          <el-table-column type="selection" width="60" />
          <el-table-column type="index" width="60" label="序号"/>
          <el-table-column :width="tableWidth.returnBoxGoodsSum.warehouseName" prop="warehouseName" label="仓库"/>
          <el-table-column :width="tableWidth.returnBoxGoodsSum.goodsName" prop="goodsName" label="商品名称" />
          <el-table-column  :width="tableWidth.returnBoxGoodsSum.goodsCode" prop="goodsCode" label="商品编码" />
          <el-table-column  :width="tableWidth.returnBoxGoodsSum.barcode" prop="barcode" label="条形码" />
          <el-table-column  :width="tableWidth.returnBoxGoodsSum.goodsCount" prop="goodsCount" label="数量" />
          <el-table-column  :width="tableWidth.returnBoxGoodsSum.taxPrice" prop="taxPrice" label="单价" />
          <el-table-column  :width="tableWidth.returnBoxGoodsSum.taxAmount" prop="taxAmount" label="金额" />
          <el-table-column  :width="tableWidth.returnBoxGoodsSum.boxNum"prop="boxNum" label="商品辅数量" >
            <template slot-scope="scope">
              <span >{{ scope.row.boxNum }}{{ scope.row.boxUnitName }}</span>
              <span >{{ scope.row.mainNum }}{{ scope.row.mainUnitName }}</span>
            </template>
          </el-table-column>
        </el-table>
        <div class="flex flex-reverse">
          <el-button @click="showReturn = false">关闭</el-button>
          <el-button @click="passReturnBox">确定</el-button>
        </div>
      </el-dialog>
      <el-dialog
        title="新增"
        :visible.sync="addReturnBillShow"
        width="40%"
      >
        <el-form :model="returnBoxBillForm" :rules="ruleForm" ref="ruleForm" label-width="100px" class="demo-ruleForm">
          <el-row>
            <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
              <el-form-item prop="busDate" label="业务日期">
                <el-date-picker
                  v-model="returnBoxBillForm.busDate"
                  type="date"
                  size="small"
                  class="date-item"
                  style="width: 100%;"
                  format="yyyy - MM - dd"
                  value-format="yyyy-MM-dd"
                />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
              <el-form-item prop="customerId" label="客户" >
                <zSelect  isLast :value.sync="returnBoxBillForm.customerId"
                          @getChange="setForm"
                          url="api/dropDown/basCustomerList"
                          :params="{ids:customerIds}"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
              <el-form-item label="部门">
                <treeselect
                  v-model="returnBoxBillForm.deptId"
                  :options="depts"
                  placeholder="选择部门"
                  style="width:  100%"
                  :normalizer="normalizer"
                />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
              <el-form-item label="业务员">
                <zSelect :value.sync="returnBoxBillForm.userId"
                         :showName="returnBoxBillForm.userName"
                         url="api/dropDown/sysUserList"
                         style="width:  100%;"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
              <el-form-item label="所属二批"  prop="sCustomerId">
                <zSelect :value.sync="returnBoxBillForm.sCustomerId"
                         :showName="returnBoxBillForm.sCustomerName"
                         :params="{ids:returnBoxBillForm.customerId}"
                         url="/api/dropDown/sCustomerList"
                         style="width:  100%;"/>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
              <el-form-item  label="仓库">
                <zSelect :value.sync="returnBoxBillForm.warehouseId"
                         :showName="returnBoxBillForm.warehouseName"
                         url="api/dropDown/basWarehouseList"
                         style="width:  100%;"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="备注">
                <el-input type="textarea" v-model="returnBoxBillForm.remark"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-button @click="submitBill">提交</el-button>
          </el-row>
        </el-form>
      </el-dialog>
      <el-dialog  title="打印预览"
                  destroy-on-close
                  v-dialogDrag
                  close-on-press-escape
                  :visible.sync="showPdf" append-to-body width="50vw">
        <j-pdf :src="pdfSrc" ></j-pdf>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import CRUD, { presenter, header, form, crud } from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import crudOperation from '@crud/CRUD.operation'
import udOperation from '@crud/UD.operation'
import pagination from '@crud/Pagination'
import crudLogisticsLoad, {orderRecycle,confirmRecycle,applyDebt,confirmDebt} from '@/api/erp/logisticsLoad'
import jTableColumnConfig from '../../../components/jTableColumnConfig/jTableColumnConfig'
import logisticsMap from '@/components/logisticsMap/map'
import { add } from '@/api/erp/basGoods'
import jPrintConfig from "../../../components/jPrintConfig/jPrintConfig";
import {customerReceipt} from "@/api/erp/logisticsLoad";
import {returnBoxPass, wareReturnBottleBoxaddOrSave, delWareReturnBottleBox} from "@/api/erp/logisticsLoad";
import {getDepts} from "@/api/system/dept";
import Treeselect from '@riophae/vue-treeselect'
import jBillDetail from "@/components/jBillDetail/jBillDetail";
import {allCustomerReceipt, batchRemoveOrder} from '@/api/erp/logisticsLoad'
import JDialog from '@/components/jDialog/jDialog'
import { customerMultiBankReceipt, updateSendAuditTime } from '@/api/erp/logisticsLoad'
import { manyTableMixin } from '@/mixins/manyTableMixin'
import RightClickMenu from '../../../components/rightClickMenu/rightClickMenu'

// crud交由presenter持有
const defaultCrud = CRUD({ title: '配送单新增', url: 'api/logisticsLoad/detail',name:'logisticsLoadDetail', sort: 'id,desc', optShow: {
    add: false,
    edit: false,
    del: false,
    download: false,
    leadingIn: false,
    downloadDetail:false,
    enable: false,
    disable: false,
    reject: true,
    pass: true,
    print: true,
    printDetail: true,
    unAccept: false, // 反验收
    accept: false, // 验收
    isShow:false,
  }, params() {
    const href = location.href.split('/')
    return {
      // id: href[href.length - 1] == 'add' ? 0 : href[href.length - 1],
      id: href[href.length - 1].split('?')[0] == 'add' ? 0 : href[href.length - 1].split('?')[0],  page: 0, size: 999,
    }
  },
  query:{
    sort:null
    // pickStatus:'5'
  }, crudMethod: { ...crudLogisticsLoad }})
const defaultForm = { id: null, code: null, name: null, type: null, saleType: null, busDate: null, receiveDate: null, sourceType: null, sourceId: null, sourceCode: null, serialNumber: null, customerOrderCode: null, customerId: null, customerCode: null, customerName: null, isContact: null, customerAreaId: null, customerAreaCode: null, customerAreaName: null, customerTypeId: null, customerTypeCode: null, customerTypeName: null, pCustomerId: null, pCustomerCode: null, pCustomerName: null, mCustomerId: null, mCustomerCode: null, mCustomerName: null, sCustomerId: null, sCustomerCode: null, sCustomerName: null, deptId: null, deptCode: null, deptName: null, userId: null, userCode: null, userName: null, warehouseId: null, warehouseCode: null, warehouseName: null, count: null, boxCount: null, taxAmount: null, noTaxAmount: null, tax: null, discountAmount: null, isCancelPick: null, pickStatus: null, pickSeq: null, pickUserId: null, pickUserCode: null, pickUserName: null, pickStartTime: null, pickEndTime: null, pickBoxCount: null, pickTaxAmount: null, pickNoTaxAmount: null, pickTax: null, isPickPrint: null, pickPrintCount: null, checkUserId: null, checkUserCode: null, checkUserName: null, checkTime: null, checkBoxCount: null, checkTaxAmount: null, checkNoTaxAmount: null, checkTax: null, isCheckPrint: null, checkPrintCount: null, isLoad: null, loadTime: null, loadOrderId: null, loadOrderCode: null, carId: null, carCode: null, carName: null, driverUserId: null, driverUserCode: null, driverUserName: null, followUserId: null, followUserIds: null, followUserCode: null, followUserName: null, packBoxCount: null, isPrint: null, printCount: null, seq: null, orderStatus: null, remark: null, orderRemark: null, createUserId: null, createUserCode: null, createUserName: null, createTime: null, updateUserId: null, updateUserCode: null, updateUserName: null, updateTime: null, auditUserId: null, auditUserCode: null, auditUserName: null, auditTime: null, closeUserId: null, closeUserCode: null, closeUserName: null, closeTime: null }
const copyFrom = Object.assign({},defaultForm)
const tableWidth = {
  customerSum:{
    customerCode:100,
    customerName:100,
    orderNum:100,
    taxAmount:100,
    emptyBoxTaxAmount:100,
    returnBoxTaxAmount:100,
    receiveAmount:120,
    boxCount:100,
    returnBoxBoxCount:100,
    volume:100,
    weight:100,
    receiptAmount:100,
    bankName:100,
    returnBoxDate:100,
    receiptDate:100,
    receiptRemark:100,
    remark:100,
    receiptCode:100,
    reachImageUrl:100
  },
  orderSum:{
    salesOrderCode:100,
    sourceCode:100,
    createTime:120,
    auditTime:120,
    customerCode:100,
    customerName:100,
    code:100,
    boxCount:100,
    taxAmount:100,
    weight:100,
    volume:100,
    remark:100,
    isReceipt:100,
    cancelStatus:100,
    receiptCode:100,
    verifyCode:100
  },
  goodsSum:{
    goodsName:100,
    goodsCode:100,
    barcode:100,
    producedDate:100,
    deadlineDate:100,
    boxUnitName:100,
    boxCount:100,
    goodsCount:100,
    boxNum:100
  },
  customerGoodsSum:{
    customerName: 100,
    goodsName: 100,
    goodsCode: 100,
    barcode: 100,
    goodsCount: 100,
    taxPrice: 100,
    taxAmount: 100,
    boxNum: 100,
  },
  returnBoxOrderSum:{
    sourceCode: 100,
    customerCode: 100,
    customerName: 100,
    count: 100,
    boxCount: 100,
    taxAmount: 100,
    remark: 100,
  },
  returnBoxGoodsSum:{
    warehouseName: 100,
    goodsName: 100,
    goodsCode: 100,
    barcode: 100,
    goodsCount: 100,
    taxPrice: 100,
    taxAmount: 100,
    boxNum: 100,
  },
  customerReturnBoxGoodsSum:{
    customerName: 100,
    goodsName: 100,
    goodsCode: 100,
    barcode: 100,
    goodsCount: 100,
    taxPrice: 100,
    taxAmount: 100,
    boxNum: 100,
  }
}
export default {
  name: 'logisticsLoadDetail',
  components: { RightClickMenu, JDialog, pagination, crudOperation, rrOperation, udOperation,logisticsMap, jPrintConfig, Treeselect, jBillDetail},
  mixins: [presenter(defaultCrud), header(), form(defaultForm), crud(),manyTableMixin],
  dicts: ['common_order_status','common_yes_or_no','common_cancel_status','t_ware_sales_invoice_pick_status'],
  data() {
    return {
      // copyForm: null,
      idDate: null,
      tabs:0,
      user:{},
      //测试数据
      customerReceiptBankList:[
      ],
      extendRightEvent:{
        returnBoxOrderList:[
          {
            fnHandler: 'addBill', // 绑定事件
            icoName: 'el-icon-plus', // icon图标
            btnName: '添加单据' // 菜单名称
          },
          {
            fnHandler: 'delBill', // 绑定事件
            icoName: 'el-icon-delete', // icon图标
            btnName: '删除单据' // 菜单名称
          },
        ]
      },
      showBankListDialog: false,
      pringDialog:false,
      auditTime: null,
      showAuditTime: false,
      info: null,
      onGPS:[],
      addReturnBillShow:false,
      showReturn:false,
      isshowcustomer: false,
      customerList: [],
      returnBoxCustomerList:[],
      goodsList: [],
      detailOrder:{},
      wareReturnBottleBoxCollectDetailOrder:{},
      customerIds:'',
      customerSelectIds:[],
      batchCollectionShow: false,
      orderList: [],
      headerQuery: {
        modelName:'wareReturnBottleBoxDetail',
        url: "api/wareReturnBottleBox/detail",
        userId:this.$store.state.user.user.userId,
      },
      wareReturnBottleBoxCollectDetail: {
        modelName:'wareReturnBottleBoxCollectDetail',
        url: "api/wareReturnBottleBoxCollect/detail",
        userId:this.$store.state.user.user.userId,
      },
      batchCollection:{
        orderId:null,
        bankId: null,
        receiptDate: null,
        receiptRemark: null,
        receiptAmount: null,
        receiptList:[]
      },
      detailParams:{
        id:0,
      },
      wareReturnBottleBoxCollectDetailParams:{
        id:0,
      },
      returnBoxBillForm:{
        busDate: null,
        customerId: null,
        userId: null,
        deptId: null,
        sCustomerId: null,
        sCustomerName: null,
        remark: null,
        warehouseId: null,
        warehouseName: null,
        loadId: null,
      },
      ruleForm:{
        busDate: [
          { required: true, message: '请输入日期', trigger: 'change' }
        ],
        customerId:[
          { required: true, message: '请输入客户', trigger: 'change' }
        ],
        sCustomerId:[
          { required: true, message: '请输入二批', trigger: 'change' }
        ],
      },
      collectionForm:{
        receiptDate: [
          { required: true, message: '请输入日期', trigger: 'change' }
        ],
        bankId:[
          { required: true, message: '请输入银行', trigger: 'change' }
        ],
      },
      scustomerList:[],
      returnBoxGoodsList: [],
      returnBoxOrderList: [],
      customerGoodsList: [],
      returnBoxCollectOrderList:[],
      selections: [],
      showPdf:false,
      pdfSrc:'',
      returnBoxCustomerGoodsList: [],
      acceptGoodsList:[],
      multiple: true,
      contextMenuData: {
        menuName: 'table',
        axis: {
          x: null,
          y: null
        },
        // 菜单选项
        menulists: [
          {
            fnHandler: 'addBill', // 绑定事件
            icoName: 'el-icon-plus', // icon图标
            btnName: '添加单据' // 菜单名称
          },
          {
            fnHandler: 'delBill', // 绑定事件
            icoName: 'el-icon-delete', // icon图标
            btnName: '删除单据' // 菜单名称
          },
        ]
      },
      rules: {
        busDate: [
          { required: true, message: '装车日期不能为空', trigger: 'blur' }
        ],
        carId: [
          { required: true, message: '车辆不能为空', trigger: 'blur' }
        ],
        driverUserId: [
          { required: true, message: '司机不能为空', trigger: 'blur' }
        ],
        followUserIds: [
          { required: true, message: '跟车不能为空', trigger: 'blur' }
        ],
      },
      permission: {
        add: ['admin', 'logisticsLoad:add'],
        edit: ['admin', 'logisticsLoad:edit'],
        del: ['admin', 'logisticsLoad:del'],
        import: ['admin', 'logisticsLoad:import'],
        export: ['admin', 'logisticsLoad:export'],
        copy: ['admin', 'logisticsLoad:copy'],
        upload: ['admin', 'logisticsLoad:upload'],
        download: ['admin', 'logisticsLoad:download'],
        pass: ['admin', 'logisticsLoad:pass'],
        reject: ['admin', 'logisticsLoad:reject'],
        closed: ['admin', 'logisticsLoad:closed'],
        invalid: ['admin', 'logisticsLoad:invalid'],
        stop: ['admin', 'logisticsLoad:stop'],
        recover: ['admin', 'logisticsLoad:recover'],
        print: ['admin', 'logisticsLoad:print'],
        salesOrderPrint: ['admin', 'logisticsLoad:salesOrderPrint'],
        goodsPrint: ['admin', 'logisticsLoad:goodsPrint'],
        follow: ['admin', 'logisticsLoad:follow'],
        accept: ['admin', 'logisticsLoad:accept'],
        appendOrder: ['admin', 'logisticsLoad:appendOrder'],
        returnBox: ['admin', 'logisticsLoad:returnBox'],
        unReturnBox: ['admin', 'logisticsLoad:unReturnBox'],
        removeCustomer: ['admin', 'logisticsLoad:removeCustomer'],
        removeOrder: ['admin', 'logisticsLoad:removeOrder'],
        removeReturnBoxOrder: ['admin', 'logisticsLoad:removeReturnBoxOrder'],
        customerReceipt: ['admin', 'logisticsLoad:customerReceipt'],
        batchCustomerReceipt: ['admin', 'logisticsLoad:batchCustomerReceipt'],
        returnBoxPass: ['admin', 'logisticsLoad:returnBoxPass'],
        returnBoxReject: ['admin', 'logisticsLoad:returnBoxReject'],
        orderRecycle: ['admin', 'logisticsLoad:orderRecycle'],
        confirmRecycle: ['admin', 'logisticsLoad:confirmRecycle'],
        applyDebt: ['admin', 'logisticsLoad:applyDebt'],
        confirmDebt: ['admin', 'logisticsLoad:confirmDebt'],
      },
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      basLineList:[], //线路
      areaList: [], // 区域
      //默认宽度
      tableWidth:{
        customerSum:{
          customerCode:100,
          customerName:100,
          orderNum:100,
          taxAmount:100,
          emptyBoxTaxAmount:100,
          returnBoxTaxAmount:100,
          receiveAmount:120,
          boxCount:100,
          returnBoxBoxCount:100,
          volume:100,
          weight:100,
          receiptAmount:100,
          bankName:100,
          returnBoxDate:100,
          receiptDate:100,
          receiptRemark:100,
          remark:100,
          receiptCode:100,
          reachImageUrl:100
        },
        orderSum:{
          salesOrderCode:100,
          sourceCode:100,
          createTime:120,
          auditTime:120,
          customerCode:100,
          customerName:100,
          code:100,
          boxCount:100,
          taxAmount:100,
          weight:100,
          volume:100,
          remark:100,
          isReceipt:100,
          cancelStatus:100,
          receiptCode:100,
          verifyCode:100
        },
        goodsSum:{
          goodsName:100,
          goodsCode:100,
          barcode:100,
          producedDate:100,
          deadlineDate:100,
          boxUnitName:100,
          boxCount:100,
          goodsCount:100,
          boxNum:100
        },
        customerGoodsSum:{
          customerName: 100,
          goodsName: 100,
          goodsCode: 100,
          barcode: 100,
          goodsCount: 100,
          taxPrice: 100,
          taxAmount: 100,
          boxNum: 100,
        },
        returnBoxOrderSum:{
          sourceCode: 100,
          customerCode: 100,
          customerName: 100,
          count: 100,
          boxCount: 100,
          taxAmount: 100,
          remark: 100,
        },
        returnBoxGoodsSum:{
          warehouseName: 100,
          goodsName: 100,
          goodsCode: 100,
          barcode: 100,
          goodsCount: 100,
          taxPrice: 100,
          taxAmount: 100,
          boxNum: 100,
        },
        customerReturnBoxGoodsSum:{
          customerName: 100,
          goodsName: 100,
          goodsCode: 100,
          barcode: 100,
          goodsCount: 100,
          taxPrice: 100,
          taxAmount: 100,
          boxNum: 100,
        },
        acceptGoodsSum: {
          goodsName: 100,
          goodsBrandName: 100,
          goodsTypeName: 100,
          goodsTagName: 100,
          warehouseName: 100,
          acceptGoodsCount: 100,
          goodsRecycleGoodsCount: 100,
          totalGoodsCount: 100,
        }
      },
      props: {
        label: 'name',
        children: 'zones'
      },
      activeName: 'first',
      pickStatus: 0,
      search: null,
      count: 1,
      filterArea: '',
      filterBas: '',
      selectTypes: [],
      isPick: false,
      customerTypeIds:null,
      lineIds: null,
      pickList: [],
      total:0,
      page:1,
      depts:[],
      size:10,
      isPickUser: false,
      isPickSep: false,
      isChildrenAdd: true,
      rowIndex:-1,
      tableList:['customerSum','orderSum','goodsSum','customerGoodsSum','returnBoxOrderSum','returnBoxGoodsSum','customerReturnBoxGoodsSum']
    }
  },
  watch: {
    filterArea(val) {
      this.$refs.treeArea.filter(val);
    },
    filterBas(val) {
      this.$refs.treeBas.filter(val);
    },
    crud(){
      this.getInfo()
    },
    'crud.order.isReturnBoxPass'(n){
      this.isChildrenAdd = this.crud.order.isReturnBoxPass == 1
    }
  },
  computed:{
    isDel(){
      const tab = this.$refs.tab
      if (tab){
        // console.log(tab._props.value)
        // console.log(this.crud.selections.length)
        return this.crud.selections.length === 0 || tab._props.value != 1
      }else {
        return this.crud.selections.length === 0 || sessionStorage.getItem('tabType')!= 1
      }
    },
    isRec(){
      const tab = this.$refs.tab
      let f=0
      if (tab){
        // console.log(tab._props.value)
        // console.log(this.crud.selections.length)
        // console.log(this.crud.selections[0].sourceType)
        // this.crud.selections.forEach(item=>{if (this.crud.selections[i].sourceType !== 1)f=1})
        for (let i of this.crud.selections){
          if (i.sourceType !== '1')f=1
        }
        // this.crud.selections.err(item=>item.sourceType !== 1)
        console.log(f)
        return this.crud.selections.length === 0 || tab._props.value != 1 || f===1
      }else {
        return this.crud.selections.length === 0 || sessionStorage.getItem('tabType')!= 1 || f===1
      }
    },
  },
  created() {
    this.getDepts()
    this.user = this.$store.state.user.user
    // this.batchCollection.receiptDate = new Date().toISOString().split('T')[0]
    this.returnBoxBillForm.loadId = this.$route.params.id
    this.batchCollection.orderId = this.$route.params.id
    // if (this.$route.params.id == 'add') {
    this.crud.order = {
      id: null,
      carId: null,
      driverUserId: null,
      followUserIds: [],
      saleType: 1,
      busDate: this.getTime(),
    }
    this.copyForm = Object.assign({},this.crud.order)
    // }
    this.tableList.forEach(item=>{
      const object = JSON.parse(localStorage.getItem(item))
      if (object){
        this.tableWidth[item] = object
      }
    })
    this.getInfo()
    this.returnBoxBillForm.busDate = new Date().toISOString().split('T')[0]
  },
  activated() {
    // this.crud.refresh()
    // this.$refs.tab._props.value
    const id = sessionStorage.getItem(this.$options.name + 'Id')
    //记录本次进入的Id
    sessionStorage.setItem(this.$options.name+'Id',this.$route.params.id)
    if(id !== this.$route.params.id){
      this.returnBoxBillForm.loadId = this.$route.params.id
      this.batchCollection.orderId = this.$route.params.id
      if(this.$route.params.id === 'add'){
        this.$set(this.crud,'order',Object.assign({},this.copyForm))
        console.log(this.copyForm)
        this.$set(this,'orderList',[])
        this.$set(this,'goodsList',[])
        this.$set(this,'customerGoodsList',[])
        this.$set(this,'returnBoxOrderList',[])
        this.$set(this,'returnBoxGoodsList',[])
        this.$set(this,'returnBoxCustomerGoodsList',[])
        this.$set(this,'returnBoxCollectOrderList',[])
        this.$set(this,'customerList',[])
        this.$set(this,'acceptGoodsList',[])
        this.wareReturnBottleBoxCollectDetailParams.id = 0
        this.detailParams.id = 0
      }else if(this.$route.params.id.indexOf('copy') !== -1){
        const copyId = this.$route.params.id.split('=')[1]
        this.wareReturnBottleBoxCollectDetailParams.id = 0
        this.detailParams.id = 0
        this.crud.toGetCopyInfo(copyId)
      }else {
        this.crud.params.id = this.$route.params.id
        this.wareReturnBottleBoxCollectDetailParams.id = 0
        this.detailParams.id = 0
        this.returnBoxBillForm = {
          busDate: new Date().toISOString().split('T')[0],
          customerId: null,
          userId: null,
          deptId: null,
          sCustomerId: null,
          sCustomerName: null,
          remark: null,
          warehouseId: null,
          warehouseName: null,
          loadId: this.$route.params.id,
        },
          this.crud.refresh()
      }
    }
  },
  mounted() {
    this.getdatatime();
    this.isChildrenAdd = this.crud.order.isReturnBoxPass == 1
    if(/add$/.test(window.location.href)){
      // this.$refs.selectCustomer.$el.getElementsByTagName('input')[0].focus()
    }else {
      this.idDate = this.$route.query.idDate
      this.idList = JSON.parse(sessionStorage.getItem(this.idDate)) || []
    }
  },
  methods: {
    detailJump(type){
      console.log(this.idList)
      if (this.idList.length){
        if (type ==='up'){
          const index = this.idList.findIndex(item=>item == this.crud.order.id)
          if (index !== 0){
            // this.$store.dispatch("tagsView/delView", this.$route);
            this.$router.push({ path:`/redirect/logistics/logisticsLoadDetail/${this.idList[index-1]}?idDate=${this.idDate}`})
          }else {
            this.$message.error('没有更多数据了')
          }
          console.log(this.$route.params.id)
        }else {
          const index = this.idList.findIndex(item=>item == this.crud.order.id)
          if (index !== this.idList.length-1){
            // this.$store.dispatch("tagsView/delView", this.$route);
            this.$router.push({ path:`/redirect/logistics/logisticsLoadDetail/${this.idList[index+1]}?idDate=${this.idDate}`})
          }else {
            this.$message.error('没有更多数据了')
          }
          console.log()
        }
      }
    },
    getdatatime(){//默认显示今天
      this.batchCollection.receiptDate= new Date();
    },
    setBankList(row){

      this.customerReceiptBankList = {
        orderId: this.crud.order.id,
        id: row.id,
        receiptRemark: row.receiptRemark,
        receiptDate: row.receiptDate,
        customerReceiptBankList:row.customerReceiptBankList
      }
      this.showBankListDialog = true
    },
    tabInvoiceType(val,isPreview,type){
      this.invoiceType = val
      this.type=type
      this.preView(isPreview)
    },
    selectRow(row, column, event){
      this.detailParams.id= row.sourceId
      this.detailOrder = row
      this.$refs['returnBillTable'].toggleRowSelection(row)
    },
    wareReturnBottleBoxCollectSelectRow(row, column, event){
      this.wareReturnBottleBoxCollectDetailParams.id= row.id
      this.wareReturnBottleBoxCollectDetailOrder = row
      this.$refs['wareReturnBottleBoxCollectTable'].toggleRowSelection(row)
    },
    showMenu() {
      if (this.crud.order.isReturnBoxPass == 1){
        return
      }
      event.preventDefault()
      var x = event.clientX
      var y = event.clientY
      // Get the current location
      this.contextMenuData.axis = {
        x, y
      }
    },
    addBank(){
      this.customerReceiptBankList.customerReceiptBankList.push({bankName:null, bankId:null, taxAmount: null})
    },
    submitBill(){
      this.$refs['ruleForm'].validate((valid) => {
        if (valid) {
          wareReturnBottleBoxaddOrSave(this.returnBoxBillForm).then(res=>{
            if (res.status === 200){
              this.addReturnBillShow = false
              this.$message.success(res.msg)
              this.returnBoxBillForm = {
                busDate: new Date().toISOString().split('T')[0],
                customerId: null,
                userId: null,
                deptId: null,
                sCustomerId: null,
                sCustomerName: null,
                remark: null,
                warehouseId: null,
                warehouseName: null,
                loadId: this.$route.params.id,
              },
                this.crud.refresh()
            }else {
              this.$message.error(res.msg)
            }
          })

        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    normalizer(node) {
      //去掉children=[]的children属性
      if (node.children == null || node.children.length == 0) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.name,
        children: node.children
      }
    },
    passReturnBox(){
      crudLogisticsLoad.returnBoxPass(this.crud.order.id).then(res=>{
        this.$message({
          message: res.msg,
          type: 'success'
        })
        this.crud.refresh()
      })
      this.showReturn = false
    },
    preView(val){
      this.isPreview = val
      this.pringDialog = true
    },
    batchCollectionSave(){
      this.$refs['collectionForm'].validate((valid) => {
        if (valid) {
          if (!this.batchCollection.receiptList.length){
            this.$message.error('请先选择明细')
            return
          }
          const data = this.customerList.map(item=>{return {id:item.id,receiptAmount:this.customerSelectIds.includes(item.id)?item.receiveAmount:0}})
          this.batchCollection.receiptList = data
          crudLogisticsLoad.batchCustomerReceipt(this.batchCollection).then(res=>{
            if (res.status === 200){
              this.batchCollectionShow = false
              this.$message.success(res.msg)
              this.batchCollection = Object.assign({},{
                orderId:this.$route.params.id,
                bankId: null,
                receiptDate: new Date().toISOString().split('T')[0],
                receiptRemark: null,
                receiptAmount: null,
                receiptList:[]
              }),
                this.crud.refresh()
            }else {
              this.$message.error(res.msg)
            }
          })

        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    print(val){
      if(val !== null){
        this.pringDialog=false
        const ids = []
        console.log('tableSum',this.$refs.tableSum)
        console.log('selection',this.$refs.tableSum.selection)
        this.$refs.tableSum.selection.forEach(item=>{ids.push(item.salesOrderId)})
        if(this.type === 'salesOrderPrint'){
          const seqList = []
          this.$refs.tableSum.selection.forEach(item=>{seqList.push({
            "salesOrderId":item.salesOrderId,
            "seq":item.index+1
          })})
          this.crud.salesOrderPrintHandler(val,ids,seqList,this.isPreview,this.type)
        }else{
          this.crud.doPrint(val,ids,this.isPreview,this.type)
        }
      }else {
        this.$message.error('请选择打印模板');
      }
    },
    //添加单据
    addBill(){
      this.addReturnBillShow = true
    },
    delBill(){
      if (!this.$refs.returnBillTable.selection.length){
        this.$message.error('请先选择需要删除的单据')
        return
      }
      let ids = []
      for(let i = 0;i < this.$refs.returnBillTable.selection.length;i++){
        ids.push(this.$refs.returnBillTable.selection[i].sourceId)
      }
      delWareReturnBottleBox(ids).then(res=>{
        if (res.status === 200){
          this.$message.success(res.msg)
        }else {
          this.$message.error(res.msg)
        }
        this.crud.refresh()
      })
    },
    // 调整
    goToPage(num,code){
      console.log(num)
      if(num == 1){
        this.$router.push({path: '/ware/wareSalesInvoiceDetail/' + code})

      }else if(num == 2){
        this.$router.push({path: '/ware/wareSalesReturnDetail/' + code})
      }else if (num == 0){
        this.$router.push({path: '/sale/salesOrderDetail/' + code})
      }
      // if (num == 0){
      //   this.$router.push({path: '/sale/salesOrderDetail/' + code})
      // }else {
      //   this.$router.push({path: '/ware/wareSalesReturn/' + code})
      // }
    },
    selectionChangeHandler01(val) {
      let ids =[]
      this.batchCollection.receiptList = val.map(item=>{
          ids.push(item.id)
          // return {id:item.id,receiptAmount:item.receiveAmount}
        }
      )
      this.customerSelectIds = ids
      let sumAmount = 0
      val.forEach(item=>{
        sumAmount += Number(item.receiveAmount)
      })
      this.batchCollection.receiptAmount =  sumAmount
      this.selections = val
    },
    isRed({ row, rowIndex }){
      if (row.receiveAmount !== row.receiptAmount){
        return {'background-color': 'red' ,}
      }
    },
    toAccept(){
      this.isshowcustomer = false
      crudLogisticsLoad.checkSplit({id:this.$route.params.id}).then(res => {
        if(res.data == 1){
          this.crud.toAccept(this.$route.params.id)
        }else{
          this.$router.push({path: '/logistics/logisticsLoadSplit/' + this.$route.params.id})
        }
        console.log('this.$route.params.id',res)
      }).catch((res) => {
      })
    },
    setBank(e,row){
      this.$set(row,'bankName',e.name)
      console.log(row)
    },
    toUnAccept(){
      crudLogisticsLoad.checkSplit({id:this.$route.params.id}).then(res => {
        if(res.data == 1){
          this.crud.toUnAccept(this.$route.params.id)
        }else{
          this.$router.push({path: '/logistics/logisticsLoadSplit/' + this.$route.params.id})
        }
      }).catch((res) => {
      })
    },
    changeBank(row,val){
      row.bankName = val.bankName
    },
    collection(row){
      let { bankId, id, orderId, receiptAmount, receiptRemark, receiptDate } = row
      const _this = this
      console.log(receiptDate)
      // receiptDate = receiptDate || new Date().toISOString().split('T')[0]
      customerReceipt({ bankId, id, orderId, receiptAmount, receiptRemark, receiptDate }).then(res=>{
        if (res.status === 200){
          this.$message({
            message: '保存成功！',
            type: 'success'
          })
          _this.crud.refresh()
        }else {
          this.$message({
            message: res.msg,
            type: 'error'
          })
        }
      }).catch(err=>{console.log(err)})
    },
    goToAdd(){
      this.$router.push({path: '/redirect/logistics/logisticsLoadAdd/' + this.$route.params.id,query:{order: this.crud.order}})
    },
    handleReturnBox(row){
      crudLogisticsLoad.returnBox(this.$route.params.id).then(res => {
        this.$message({
          message: '回箱入库成功',
          type: 'success'
        })
        this.crud.refresh()
      }).catch((res) => {
      })
    },
    getDepts() {
      getDepts({status: 1}).then(res => {
        this.depts = res
      })
    },
    delBank(list,index){
      list.customerReceiptBankList.splice(index,1)
    },
    unReturnBoxHandle(){
      crudLogisticsLoad.returnBoxReject(this.$route.params.id).then(res => {
        this.$message({
          message: '反审回箱成功',
          type: 'success'
        })
        this.crud.refresh()
      }).catch((res) => {
      })
    },
    handleUnReturnBox(){
      crudLogisticsLoad.unReturnBox(this.$route.params.id).then(res => {
        this.$message({
          message: '回箱反审成功',
          type: 'success'
        })
        this.crud.refresh()
      }).catch((res) => {
      })
    },
    delAddRow(row){
      if(this.$route.params.id !== 'add'){
        this.$confirm('此操作将直接删除此条产品记录, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let data = {
            id:row.row.id,
            orderId: row.row.orderId,
          }
          console.log('removeOrder',data)
          crudLogisticsLoad.removeCustomer(data).then(res => {
            this.customerList.splice(row.$index, 1)
            console.log('this.$route.params.id',res)
            this.crud.toQuery()
          }).catch((res) => {
          })
        }).catch(() => {
          // this.$message({
          //   type: 'info',
          //   message: '已取消删除'
          // });
        });
      }else{
        this.customerList.splice(row.$index, 1)
      }
    },
    delAddRowBoxOrder(row){
      if(this.$route.params.id !== 'add'){
        this.$confirm('此操作将直接删除此条数据, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let data = {
            id:row.row.id,
            orderId: row.row.orderId,
          }
          console.log('removeOrder',data)
          crudLogisticsLoad.removeReturnBoxOrder(data).then(res => {
            this.goodsList.splice(row.$index, 1)
            console.log('this.$route.params.id',res)
            this.crud.toQuery()
          }).catch((res) => {
          })
        }).catch(() => {
          // this.$message({
          //   type: 'info',
          //   message: '已取消删除'
          // });
        });
      }else{
        this.goodsList.splice(row.$index, 1)
      }
    },
    changeCustomerReceiptBankListName(e,row){
      row.bankName = e.name
    },
    orderRecycle(){
      const orderId = this.crud.order.id
      const ids = this.$refs.tableSum.selection.map(item=>item.id).join(',')
      orderRecycle({orderId,ids}).then(res=>{
        if (res.status === 200){
          this.$message.success(res.msg)
          this.crud.refresh()
        }else {
          this.$message.error(res.msg)
        }
      })
    },
    confirmRecycle(){
      const orderId = this.crud.order.id
      const ids = this.$refs.tableSum.selection.map(item=>item.id).join(',')
      confirmRecycle({orderId,ids}).then(res=>{
        if (res.status === 200){
          this.$message.success(res.msg)
          this.crud.refresh()
        }else {
          this.$message.error(res.msg)
        }
      })
    },
    delAddRowOrder(){
      const that = this
      const ids = this.$refs.tableSum.selection.map(item=>item.id).join(',')
      const data = {orderId:this.$refs.tableSum.selection[0].orderId,ids}
      if(this.$route.params.id !== 'add'){
        this.$confirm(`确认删除选中的${this.$refs.tableSum.selection.length}条数据?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          // that.crud.delAllLoading = true
          // this.crud.doDelete(datas)
          // let data = {
          //   id:row.row.id,
          //   orderId: row.row.orderId,
          // }
          // console.log('removeOrder',data)
          batchRemoveOrder(data).then(res => {
            that.crud.refresh()
          }).catch((res) => {
          })
        }).catch(() => {
          // this.$message({
          //   type: 'info',
          //   message: '已取消删除'
          // });
        });
      }else{
        this.orderList.splice(row.$index, 1)
      }
    },
    getInfo(){
      crudLogisticsLoad.detail({id:this.$route.params.id}).then(res => {
        if (res){
          this.crud.order = res.data.order
          this.customerList= res.data.customerList
          this.goodsList= res.data.goodsList
          this.orderList= res.data.orderList
          this.returnBoxGoodsList= res.data.returnBoxGoodsList
          this.returnBoxOrderList= res.data.returnBoxOrderList
          this.returnBoxCollectOrderList = res.data.returnBoxCollectOrderList
          this.customerGoodsList= res.data.customerGoodsList
          this.returnBoxCustomerGoodsList= res.data.returnBoxCustomerGoodsList
          this.acceptGoodsList = res.data.acceptGoodsList
          let ids = ''
          for(let i in this.customerList){
            ids += this.customerList[i].customerId+','
          }
          this.customerIds = ids
        }
        console.log('this.$route.params.id',res)
      }).catch((res) => {
      })
    },

    setForm(val){
      this.returnBoxBillForm.userId = val.userId
      this.returnBoxBillForm.userName = val.userName

      this.returnBoxBillForm.deptId = val.deptId
      this.returnBoxBillForm.deptName = val.deptName

      this.returnBoxBillForm.sCustomerId = null
      this.returnBoxBillForm.sCustomerName = null
      if (val.scustomerList.length === 1){
        this.returnBoxBillForm.sCustomerId = val.scustomerList[0].scustomerId
        this.returnBoxBillForm.sCustomerName = val.scustomerList[0].scustomerName
      }

      this.returnBoxBillForm.warehouseId = val.warehouseId
      this.returnBoxBillForm.warehouseName = val.warehouseName

    },
    removeStorage(){
      this.tableList.forEach(item=>{
        localStorage.removeItem(item)
        this.tableWidth = tableWidth
        console.log(this.tableWidth)
      })
    },
    selectionChangeHandler(val) {
      this.crud.selections = val
    },
    toDetailPlus(e){
      this.onGPS = e.loaction
      if (this.rowIndex === e.index){
        this.rowIndex = -1
      }else {
        this.rowIndex = e.index
      }
    },
    getTime(date = new Date()){
      var y = date.getFullYear();
      var m = date.getMonth() + 1;
      m = m < 10 ? ('0' + m) : m;
      var d = date.getDate();
      d = d < 10 ? ('0' + d) : d;
      var h = date.getHours();
      h=h < 10 ? ('0' + h) : h;
      var minute = date.getMinutes();
      minute = minute < 10 ? ('0' + minute) : minute;
      var second=date.getSeconds();
      second=second < 10 ? ('0' + second) : second;
      // +' '+h+':'+minute+':'+second;
      return y + '-' + m + '-' + d+' '+h+':'+minute+':'+second
    },
    async saveBankList(e){
      try {
        for (let i of e){
          i.customerReceiptBankList = i.customerReceiptBankList.filter(item=>item.bankId)
          await customerMultiBankReceipt(i)
        }
      }catch (e){
        return Promise.reject(e)
      }
      return Promise.resolve('success')
    },
    toPicking(row){
      // if(row.length == 0){
      //   this.$message({
      //     message: '请勾选一笔发货单！',
      //     type: 'error'
      //   })
      //   return false
      // }
      this.$refs['form'].validate((valid) => {
        if (valid) {
          let followUserIds =this.crud.order.followUserIds? typeof (this.crud.order.followUserIds)=='string'?this.crud.order.followUserIds:this.crud.order.followUserIds.join(','): ''
          this.crud.order.followUserIds =followUserIds
          this.crud.order.orderList = row
          crudLogisticsLoad.add(this.crud.order).then(res => {
            if (this.$route.params.id == 'add') {
              this.$router.replace('/redirect/logistics/logisticsLoadDetail/'+id)
            }
            this.$message({
              message: '保存成功！',
              type: 'success'
            })
            // this.crud.toQuery()
            // bankList.length && this.saveBankList(bankList).then(res=>{this.crud.toQuery()}).catch(err=>{console.log(err.data.msg)})
          }).catch((res) => {
          })
        }
      })
    },

    saveBank(i){
      this.saveBankList([this.customerReceiptBankList]).then(res=>{
        this.$message.success('保存成功')
        this.showBankListDialog = false
        this.crud.refresh()
      }).catch(err=>{this.$message.error(err.data.msg)})
    },
    saveReceipt(){
      const date = new Date().toLocaleString('chinese',{hour12:false}).replace(/\//g,'-')
      const receiptList = this.customerList.map(item=> {
        const { bankId, id, orderId, receiptAmount, receiptRemark, receiptDate } = item
        return { bankId, id, orderId, receiptAmount, receiptRemark, receiptDate: receiptDate || date }
      }).filter(item=>item.receiptAmount !== null || item.receiptAmount !== '')
      allCustomerReceipt({ receiptList }).then(res=>{
        if (res.status === 200){
          this.$message({
            message: '保存成功！',
            type: 'success'
          })
          this.crud.refresh()
        }else {
          this.$message({
            message: res.msg,
            type: 'error'
          })
        }
      }).catch(err=>{console.log(err)})
    },
    changWidth(newWidth, old, column,type){
      const object = this.tableWidth[type]
      object[column.property] = newWidth.toFixed(2)
      localStorage.setItem(type,JSON.stringify(object))
    },
    handleSizeChange(val) {
      this.size = val
      this.toPicking()
      console.log(`每页 ${val} 条`);
    },
    handleCurrentChange(val) {
      this.page = val
      this.toPicking()

    },
    handleCheckChange(data, checked, indeterminate) {
      console.log(data, checked, indeterminate);
      const rows = this.$refs.treeBas.getCheckedNodes()
      if (rows.length == 0) {
        return false
      }
      this.selectTypes = rows.map(r => r.id)
      this.query.customerAreaIds = this.selectTypes.join(',')
      this.crud.refresh()
      console.log('selectTypes', this.selectTypes)
      this.getGoodsList()
    },
    selectRow01(row){
      this.$refs['collectTable'].toggleRowSelection(row)
    },
    handleCheckLineChange(data, checked, indeterminate) {
      console.log(data, checked, indeterminate);
      const rows = this.$refs.treeArea.getCheckedNodes()
      if (rows.length == 0) {
        return false
      }
      this.selectTypes = rows.map(r => r.id)
      this.query.lineIds = this.selectTypes.join(',')
      this.crud.refresh()
      this.getGoodsList()
    },
    sumRow(param) {
      const { columns, data } = param
      const sums = []
      const summaryList = ['boxCount', 'taxAmount', 'productCount', 'totalGrossWeight', 'totalNetWeight', 'count', 'noTaxAmount',
        'discountAmount', 'acceptBoxCount', 'acceptGoodsCount', 'acceptTaxAmount', 'acceptTax', 'cancelAmount', 'unCancelAmount', 'goodsCount',
        'checkGoodsCount', 'inAmount', 'balanceAmount', 'tax', 'acceptBoxNum', 'acceptMainNum', 'acceptNoTaxAmount', 'enterGoodsCount',
        'enterBoxCount', 'enterBoxNum', 'enterMainNum', 'enterTaxAmount', 'enterNoTaxAmount', 'enterTax', 'returnGoodsCount', 'returnBoxCount',
        'returnBoxNum', 'returnMainNum', 'returnTaxAmount', 'returnNoTaxAmount', 'returnTax', 'sendGoodsCount', 'sendBoxCount', 'sendBoxNum',
        'sendMainNum', 'sendTaxAmount', 'sendNoTaxAmount', 'sendTax', 'returnBottleBoxGoodsCount', 'returnBottleBoxBoxCount', 'returnBottleBoxBoxNum',
        'returnBottleBoxMainNum', 'returnBottleBoxTaxAmount', 'returnBottleBoxNoTaxAmount', 'returnBottleBoxTax', 'buyGoodsCount', 'buyBoxCount',
        'buyBoxNum', 'buyMainNum', 'buyTaxAmount', 'buyNoTaxAmount', 'buyTax', 'saleGoodsCount', 'saleBoxCount', 'saleBoxNum', 'saleMainNum',
        'saleTaxAmount', 'saleNoTaxAmount', 'saleTax', 'allotGoodsCount', 'form.allotBoxCount', 'allotBoxNum', 'allotMainNum', 'allotTaxAmount',
        'allotNoTaxAmount', 'allotTax', 'lossGoodsCount', 'lossBoxCount', 'lossBoxNum', 'lossMainNum', 'lossTaxAmount', 'lossNoTaxAmount', 'lossTax',
        'overGoodsCount', 'overBoxCount', 'overBoxNum', 'overMainNum', 'overTaxAmount', 'overNoTaxAmount', 'overTax', 'allotBoxCount','emptyBoxTaxAmount',
        'returnBoxTaxAmount','receiveAmount'
      ]
      columns.forEach((column, index) => {
        let selectSum = 0
        if (index === 0) {
          sums[index] = <p>
            选中合计
            <hr />
            合计
          </p>
          column.colSpan = 2
          return
        }
        if (this.selections.length > 0) {
          this.selections.map(sel => {
            for (const key in sel) {
              if (column.property === key) {
                if (summaryList.includes(key)) {
                  selectSum = (parseFloat(sel[key]) + (parseFloat(selectSum || 0))).toFixed(2)
                }
              }
            }
          })
        }
        if (summaryList.includes(column.property)) { // 指定哪一列合计 如果需要全部合计 去掉这个判断即可
          const values = data.map((item) => Number(item[column.property]))
          if (!values.every((value) => isNaN(value))) {
            const sum = values.reduce((prev, curr) => {
              const value = Number(curr)
              if (!isNaN(value)) {
                const sum = prev + curr
                return sum
              } else {
                return prev
              }
            }, 0)
            sums[index - 1] = <p>{selectSum}<hr />{sum.toFixed(2)}</p>
          } else {
            sums[index - 1] = ''
          }
        }
      })
      return sums
    },
    handleClickPickStatus(tab, event){
      this.tabs=this.$refs.tab._props.value
      sessionStorage.setItem('tabType',this.tabs)
      this.$set(this.crud,'selections',[])
      this.$refs.tab._props.value == 2&& this.$set(this.crud,'selections',this.$refs.tableSum.selection)
      // this.query.lineIds = ''
      // this.query.customerAreaIds = ''
      // this.crud.refresh()
    },
    filterNode(value, data) {
      if (!value) return true;
      return data.name.indexOf(value) !== -1;
    },
    filterNodeLine(value, data) {
      if (!value) return true;
      return data.name.indexOf(value) !== -1;
    },
    // 获取数据前设置好接口地址
    [CRUD.HOOK.beforeRefresh]() {
      return true
    }, // 新增与编辑前做的操作
    [CRUD.HOOK.afterRefresh](crud, form) {
      this.getInfo()
    },
    handleClick(tab, event) {
      if(this.activeName == 'first'){
        this.basLine()
      }else{
        this.getArea()
      }
    },
    async updatedAuditTime(){
      if (this.auditTime){
        const {msg} = await crudLogisticsLoad.updateSendAuditTime({auditTime:this.auditTime,id:this.crud.order.id})
        this.$message.success(msg)
        this.auditTime = null,
          this.showAuditTime = false
        this.crud.refresh()
      }else {
        this.$message.error('请先选择发货时间')
      }
    },
    handleClick1(tab, event){
      console.log(111)
      console.log(tab, event);
    },
    checkDebt(requireStatus){
      const tab = this.$refs.tab
      let flag = 0
      if (tab){
        for (let i of this.crud.selections){
          if (i.debtStatus === requireStatus) {
            if((requireStatus === 0 && this.user.userId == this.crud.order.driverUserId)
                || (requireStatus === 1 && this.user.userId == i.userId)){
              flag = 1
            }
          }
        }
        return this.crud.selections.length !== 1 || tab._props.value != 0 || flag === 0
      }else {
        return true
      }
    },
    applyDebt(){
      const orderId = this.crud.order.id
      const id = this.crud.selections[0].id
      applyDebt({orderId,id}).then(res=>{
        if (res.status === 200){
          this.$message.success(res.msg)
          this.crud.refresh()
        }else {
          this.$message.error(res.msg)
        }
      })
    },
    confirmDebt(){
      const orderId = this.crud.order.id
      const id = this.crud.selections[0].id
      confirmDebt({orderId,id}).then(res=>{
        if (res.status === 200){
          this.$message.success(res.msg)
          this.crud.refresh()
        }else {
          this.$message.error(res.msg)
        }
      })
    },
  }
}
</script>

<style lang="scss" rel="stylesheet/scss" scoped>
.table-img {
  display: inline-block;
  text-align: center;
  background: #ccc;
  color: #fff;
  white-space: nowrap;
  position: relative;
  overflow: hidden;
  vertical-align: middle;
  width: 32px;
  height: 32px;
  line-height: 32px;
}
.content{
  display: flex;
  align-items: top;
  justify-content: space-between;
  .left{
    width: 15%;
    //margin-top: 11px;
    .top{
      margin-bottom: 10px;
    }
  }
  .center{
    margin: 0 1%;
    width: 60%;
  }
  .right{
    width: 30%;
  }
}
.fotter{
  display: flex;
  align-items: center;
  height: 50px;
  line-height: 50px;
  margin-top: 20px;
  justify-content: space-between;
  .fotter-left{
    width: 50%;
    display: inline-block;
  }
  .fotter-right{
    width: 50%;
    text-align: right;
    display: inline-block;
  }
}
.fotters{
  width: 100%;
  text-align: center;
}
.isReturnBox{
  position: absolute;
  right: 10%;
  width: 200px;
  height: 100px;
  border: rgba(255,0,0,0.3) 8px solid;
  display: flex;
  justify-content: center;
  align-items: center;
  color: rgba(255,0,0,0.3);
  font-size: 50px;
  transform: rotate(25deg);
  z-index: -1;
}
.green{
  color: #008B00
}
.old{
  color: #409eff
}
.banks{
  color: blue;
  cursor: pointer;
}
.red{
  color: red !important;
}
</style>

